<script async setup>
import { reactive ,unref,computed} from "vue";
import axios from 'axios';
import "@/assets/font-awesome-4.7.0/css/font-awesome.css";
import MyDateSlider from "./MyDateSlider.vue";
import memCom from "./mem.vue"
import freechild from "./freechild.vue"

import {formatDate, _dateTimeFormatter2Number} from "../utils/dateutil"
import {useFetch} from "../utils/fetch"


import popUp from "./freechildsPopup.vue"

import {
  Check,
  Delete,
  Edit,
  Message,
  Search,
  Star,
} from '@element-plus/icons-vue'

var wkDate = ref(new Date());


var formatedWkdateStr = computed(()=>{
  return formatDate(wkDate.value);
})

const dateChangedHandler = function (secondTime) {
  wkDate.value = new Date(secondTime * 1000);
};
/**
const freeman = reactive([
  {
    id: "C0001",
    name: "C1",
    tech: "java",
    level: "PG",
    isFree: true,
    history: [
      {
        prjId: 1,
        prjName: "todoList",
        startDate: "2023-01-12",
        endDate: "2023-03-15",
      },
      {
        prjId: 2,
        prjName: "tizhi",
        startDate: "2023-03-16",
        endDate: "2023-04-31",
      },
    ],
  },
  {
    id: "C0002",
    name: "C2",
    tech: "js",
    level: "SE",
    isFree: true,
    history: [
      {
        prjId: 1,
        prjName: "todoList",
        startDate: "2023-01-12",
        endDate: "2023-03-15",
      },
      {
        prjId: 2,
        prjName: "tizhi",
        startDate: "2023-03-16",
        endDate: "2023-04-31",
      },
    ],
  },
  {
    id: "C0003",
    name: "C3",
    tech: "Cobol",
    level: "PG",
    isFree: true,
    history: [
      {
        prjId: 1,
        prjName: "todoList",
        startDate: "2023-01-12",
        endDate: "2023-03-15",
      },
      {
        prjId: 2,
        prjName: "tizhi",
        startDate: "2023-03-16",
        endDate: "2023-04-31",
      },
    ],
  },
  {
    id: "C0004",
    name: "C4",
    tech: "java",
    level: "PL",
    isFree: true,
    history: [
      {
        prjId: 1,
        prjName: "todoList",
        startDate: "2023-01-12",
        endDate: "2023-03-15",
      },
      {
        prjId: 2,
        prjName: "tizhi",
        startDate: "2023-03-16",
        endDate: "2023-04-31",
      },
    ],
  },
  {
    id: "C0005",
    name: "C5",
    tech: "vue",
    level: "SL",
    isFree: true,
    history: [
      {
        prjId: 1,
        prjName: "todoList",
        startDate: "2023-01-12",
        endDate: "2023-03-15",
      },
      {
        prjId: 2,
        prjName: "tizhi",
        startDate: "2023-03-16",
        endDate: "2023-04-31",
      },
    ],
  },
]);
 */


/*
const tizhi = reactive([
  {
    prjId: 1,
    prjName: "toListPrj",
    slList: [
      {
        slid: "SL0",
        leader: {
          id: "C0006",
          name: "C6",
          tech: "java",
          level: "SE",
          gangwei: "SL",
        },
        memList: [
          {
            id: "C0007",
            name: "C7",
            tech: "java",
            level: "SE",
            gangwei: "MEM",
          },
          {
            id: "C0008",
            name: "C8",
            tech: "java",
            level: "SE",
            gangwei: "MEM",
          },
          {
            id: "C0009",
            name: "C9",
            tech: "java",
            level: "SE",
            gangwei: "MEM",
          },
        ],
      },
      {
        slid: "SL1",
        leader: {
          id: "C0010",
          name: "C10",
          tech: "java",
          level: "SE",
          gangwei: "SL",
        },
        memList: [
          {
            id: "C0011",
            name: "C11",
            tech: "java",
            level: "SE",
            gangwei: "MEM",
          },
          {
            id: "C0012",
            name: "C12",
            tech: "java",
            level: "SE",
            gangwei: "MEM",
          },
          {
            id: "C0013",
            name: "C13",
            tech: "java",
            level: "SE",
            gangwei: "MEM",
          },
        ],
      },
    ],
  },
  {
    prjId: 2,
    prjName: "tizhiPrj",
    slList: [
      {
        slid: "SL0",
        leader: {
          id: "C0014",
          name: "C14",
          tech: "java",
          level: "SE",
          gangwei: "SL",
        },
        memList: [],
      },
      {
        slid: "SL1",
        leader: null,
        memList: [
          {
            id: "C0015",
            name: "C15",
            tech: "java",
            level: "SE",
            gangwei: "MEM",
          },
          {
            id: "C0016",
            name: "C16",
            tech: "java",
            level: "SE",
            gangwei: "MEM",
          },
          {
            id: "C0017",
            name: "C17",
            tech: "java",
            level: "SE",
            gangwei: "MEM",
          },
        ],
      },
    ],
  },
]);
*/

var tizhi = ref(null);
var oldtizhi = null;
var freeman = ref(null);
var error = ref(null);
var teamdata = ref(null);
let currentDateParam = _dateTimeFormatter2Number(wkDate.value);
await axios.post("http://localhost:8081/api/alltizhi",currentDateParam).then(function(response){
   console.log(response.data);
   teamdata = response.data;
   console.log("set oldtizhi. 257");
   oldtizhi = JSON.parse(JSON.stringify(response.data.tizhi)) // OK，深拷贝对象就是所有属性的值都复制了一份。
   //oldtizhi = {...response.data.tizhi} ; // NG . 浅拷贝获得的对象跟着tizhi对象走。因为，属性值还是原来对象的。
   tizhi.value = response.data.tizhi;
   freeman.value = response.data.freeman;
}).catch(function(err){
  error.value = err;
})
 

const printTiZhi = function(){
  console.log(tizhi.value);
}

const addsl = function (slList) {
  console.log("addsl()===>" + event.target.id);
  console.log(slList);
  if (slList != null) {
    slList.push({
      slid: "SL" + (slList.length + 1),
      leader: null,
      memList: [],
    });
  } else {
    slList.push({ slid: "SL1", leader: null, memList: [] });
  }
};
const delsl = function (slList) {
  console.log("delsl");
  if (slList != null && slList.length > 0) {
    // check 有人的组不让删除
    var sl = slList[slList.length - 1];
    if (
      (sl != null && sl.leader != null) ||
      (sl.memList != null && sl.memList.length > 0)
    ) {
      // alert("请先删除组员才能删除组！");
      ElNotification({
        title: "Warning",
        message: "请先删除组员才能删除组！",
        type: "warning",
        showClose: true,
      });
      return;
    }
    // console.log(sl.leader.name);
    slList.pop();
  }
};

// 所有的Dom加载完成之后，设置所有人员的拖拽属性
const dragStartHandle = function (man, e) {
  console.log("start dragStartHandle....");
  //debugger
  e.dataTransfer.setData("manid", man.id);
  console.log("end dragStartHandle....");
};

const dragOverHandler = function (e) {
  //取消事件默认行为
  e.preventDefault();
};

/** 2. drp to tmpzone .向tmp里拖拽的 */
const tmpzoneDropHandler = function (e) {
  console.log("in tmpzoneDropHandler");

   // step1. 先分析drag
  var manid = e.dataTransfer.getData("manid");
  var retFreeMan = findManFromFreeman(manid);
  var man = null;
  if(Object.keys(retFreeMan).length==0){
    // drag不是freeman。那么就是team呗。
    var dragTeamNode = findMemFromTeamOnlyById(manid);
    if(Object.keys(dragTeamNode).length==0){
      // 也不是team的节点。那不可能
      // alert("拽的既不是暂存池也不是team里的人员！！")
      ElNotification({
        title: "Warning",
        message: "拽的既不是暂存池也不是team里的人员！！！",
        type: "warning",
        showClose: true,
      });
      return
    }
    man = dragTeamNode; // source 
   
    if(dragTeamNode.mem.isFree){
      
    }else{
      //alert("项目组成员不能拖进暂存池，请用另一个画面先释放该成员")
      ElNotification({
        title: "Warning",
        message: "现有成员不能拖拽到暂存池。请先在另一个画面释放该成员！",
        type: "warning",
        showClose: true,
      });
      return  
    }
  }else{
    man = retFreeMan; // source
  }
  console.log("draged man==>",man);

  // step2.再分析drop
  let dropDom = e.target;
  if(dropDom.className.indexOf("freechild")!=-1){
    // drop to tmp.freechild
    let dropNode = findManFromFreeman(e.target.id); // tmp.child
    drop2TmpChild(man,dropNode);

  }else if( dropDom.className.indexOf("leftMiddle")!=-1){
    // drop to tmp.space
    drop2TmpSpace(man,e);
  }else if(dropDom.className.indexOf("el-only-child")!=-1){
    // drop to freechild.span
    let freechildDom = dropDom.parentElement
    let dropNode = findManFromFreeman(freechildDom.id); // tmp.child
    drop2TmpChild(man,dropNode);
  }
  else{
    // 不可能
    console.log("不可能 do nothing dropDom.id="+dropDom.id+", dropDom.className="+dropDom.className );
    return;
  }

}

const drop2TmpChild = function(man,dropNode){ //
 
  if(man.findFromFreeman){
    //tmp.child=>tmp.child
    // let tmp = man.mem;
    freeman[dropNode.i] = man.mem;
    freeman[man.i] = dropNode.mem;
  }else{
    //team=>tmp.child
    if(man.isLeader){
      //sl1.leader=>tmp.child
      freeman.value.splice(dropNode.i,0,man.mem);
      if(man.sl.memList!=null && man.sl.memList.length>0){
        man.sl.leader = man.sl.memList[0];
        man.sl.memList.splice(0,1);
      }else{
        man.sl.leader =null;
      }
    }else{
      //sl1.member=>tmp.child
      freeman.value.splice(dropNode.i,0,man.mem);
      man.sl.memList.splice(man.i,1);
    }
  }
}

const drop2TmpSpace = function(man,e){
  
  if(man.findFromFreeman){
    //tmp.child=>tmp.space
    console.log("tmp.child=>tmp.space");
    freeman.value.splice(man.i,1);
    freeman.value.push(man.mem);
  }else{
    //team=>tmp.space
    if(man.isLeader){
      //team.leader=>tmp.space
      console.log("team.leader=>tmp.space");
      freeman.value.push(man.mem)
      man.sl.leader 
      if(man.sl.memList!=null && man.sl.memList.length>0){
        man.sl.leader= man.sl.memList[0]
        man.sl.memList.splice(0,1)
      }else{
        man.sl.leader = null;
      }
    }else{
      //team.member=>tmp.space
      console.log("team.member=>tmp.space");
      freeman.value.push(man.mem)
      man.sl.memList.splice(man.i,1);
    }
  }
  
}

/** 1. drop to sl .往SL上拖拽的处理。或者SL上的MEMBER。或SL上的LEADER上拖拽都在这里处理。 */
const slDropHandler = function (sl, e) {
  console.log("start slDropHandler()...");

  var man = null;
  // step1. 先分析drag
  var manid = e.dataTransfer.getData("manid");
  var retFreeMan = findManFromFreeman(manid);
  
  if(Object.keys(retFreeMan).length==0){
    // drag不是freeman。那么就是team呗。
    var dragTeamNode = findMemFromTeamOnlyById(manid);
    
    if(Object.keys(dragTeamNode).length==0){
      // 也不是team的节点。那不可能
      // alert("拽的既不是暂存池也不是team里的人员！！")
      ElNotification({
        title: "Warning",
        message: "拽的既不是暂存池也不是team里的人员！！！",
        type: "warning",
        showClose: true,
      });
      return
    }
    man = dragTeamNode; // source 
  }else{
    man = retFreeMan; // source
  }
  console.log("draged man==>",man);


  // step2. 再分析drop
  var targetDom = e.target;
  if(targetDom.className.indexOf("member")!=-1){
    // drop to team.member
    console.log("drop to team.member");

    drop2TeamMember(man,e,sl);
  }else if( targetDom.className.indexOf("leader")!=-1){
    // drop to team.leader
    console.log("drop to team.leader");
    drop2TeamLeader(man,e,sl);

  }else if(targetDom.className.indexOf("sl")!=-1){
    // drop to team.sl
    console.log("drop to team.sl");
    drop2TeamSl(man,e,sl);
  
  }else{
    // do nothing
   console.log("do nothing targetDom.className="+targetDom.className);
  }

  console.log("end slDropHandler()...");
};

const drop2TeamMember = function(man,e,sl){
  var dropNode = findMemFromTeamOnlyById(e.target.id);
    if(man.findFromFreeman){
      // tmp=>team.member
      console.log("tmp=>team.member");
      freeman.value.splice(man.i,1);
      sl.memList.splice(dropNode.i,0,man.mem);

    }else{
      // team=>team.member
      console.log("team=>team.membe");
      if(man.isLeader){
        // team.leader=>team.member
        console.log("team.leader=>team.member");
        if(man.prj.prjId != dropNode.prj.prjId){
          //alert("不允许项目间调整")
          ElNotification({
            title: "Warning",
            message: "不允许项目间调整,请现在另一个画面释放该成员！",
            type: "warning",
            showClose: true,
          });
          return
        }
        if(man.sl.slid == dropNode.sl.slid){
          // sl.leader=>sl.member
          console.log("组内调整 sl.leader=>sl.member");
          if(dropNode.sl.memList!=null && dropNode.sl.memList.length>0){
              
              if(dropNode.mem.id == dropNode.sl.memList[0].id){
                // sl.leader==>sl.memberList[0]
                console.log("sl.leader==>sl.memberList[0] : do nothing!!");
                //do nothing
              }else{
               // sl.leader==>sl.memberList[0]以外
               console.log("组内调整 sl.leader==>sl.memberList[0]以外");
                dropNode.sl.memList.splice(dropNode.i,0,man.mem);
                dropNode.sl.leader = dropNode.sl.memList[0];
                dropNode.sl.memList.splice(0,1);
              }
          }else{
            // 没有memberList
            // 不可能
            console.log("不可能");
          }
        }else{
          //组间调整 sl2.leader=>sl.member
          sl.memList.splice(dropNode.i,0,man.mem);
          if(man.sl.memList!=null && man.sl.memList.length>0){
            man.sl.leader = man.sl.memList[0]
            man.sl.memList.splice(0,1)
          }else{
            man.sl.leader = null;
          }

        }
      }else{
        //team.member=>team.member
        console.log("team.member=>team.member");
        if(dropNode.prj.prjId!=man.prj.prjId){
          //alert("不允许组间调整")
          ElNotification({
            title: "Warning",
            message: "不允许项目间调整,请现在另一个画面释放该成员！",
            type: "warning",
            showClose: true,
          });
          return
        }
        if(dropNode.sl.slid == man.sl.slid){
          // sl1.team.member=>sl1.team.member
          console.log("sl1.team.member=>sl1.team.member");
          let tmp = man.mem;
          sl.memList[man.i] = sl.memList[dropNode.i];
          sl.memList[dropNode.i] = tmp;
        }else{
          // sl2.team.member=>sl1.team.member
          console.log("sl2.team.member=>sl1.team.member");
          sl.memList.splice(dropNode.i,0,man.mem);
          man.sl.memList.splice(man.i,1);
        }
      }
      
    }
}
const drop2TeamLeader = function(man,e,sl){
  var dropMan = findMemFromTeamOnlyById(e.target.id);
   
    if(man.findFromFreeman){
      // tmp=>team.leader
      console.log("tmp=>team.leader");
      freeman.value.splice(man.i,1);
      if(sl.leader!=null){
        sl.memList.unshift(sl.leader);
      }
      sl.leader = man.mem;
    }else{
      // team=>team.leader
      console.log("team=>team.leader");
      if(dropMan.prj.prjId == man.prj.prjId){
        if(dropMan.sl.slid == man.sl.slid){
          // 组内
          if(man.i==0){
            // first member ==> same sl leader
            let tmp = sl.leader;
            sl.leader = man.mem;
            sl.memList[0]=tmp;
          }else{
            // same sl . not first member ==> same sl.leader
            let tmp = sl.leader;
            sl.leader = man.mem;
            sl.memList.splice(man.i,1);
            sl.memList.unshift(tmp);
          }
        }else{
          // 组间
         
          // target
          sl.memList.unshift(sl.leader)
          sl.leader = man.mem;

          // source
          if(man.isLeader){
            //sl2.leader=>sl.leader
            if(man.sl.memList!=null && man.sl.memList.length>0){
              man.sl.leader = man.sl.memList[0];
              man.sl.memList.splice(0,1)
            }else{
              man.sl.leader= null;
            }
          }else{
            // sl2.member => sl.leader
            console.log("sl2.member => sl.leader");
            // source
            man.sl.memList.splice(man.i,1) 
          }
        }
      }else{
        // alert("不允许项目间拖拽")
        ElNotification({
            title: "Warning",
            message: "不允许项目间调整,请现在另一个画面释放该成员！",
            type: "warning",
            showClose: true,
          });
        return
      }
      
      
    }
}

const drop2TeamSl = function(man,e,sl){
  if(man.findFromFreeman){
      // tmp=>team.sl
      console.log("tmp=>team.sl")
      sl.memList.push(man.mem);
      freeman.value.splice(man.i,1)
    }else{
      // team=>team.sl

      let dropSlDom = e.target;
      let dropPrjDom = e.target.parentElement.parentElement;
    
      if(dropPrjDom.id != man.prj.prjId){
        // alert("不允许项目间调整")
        ElNotification({
            title: "Warning",
            message: "不允许项目间调整,请现在另一个画面释放该成员！",
            type: "warning",
            showClose: true,
          });
        return
      }

      if(dropSlDom.id == man.sl.slid){
        // 组内交换
        console.log("组内交换");
        if(man.isLeader){
          // sl1.leader=>sl1.空白
          console.log("组内交换 sl1.leader=>sl1.空白");
          if(sl.memList!=null && sl.memList.length>0){
            let tmp = sl.leader;
            sl.leader = sl.memList[0];
            sl.memList.splice(0,1)
            sl.memList.push(tmp)
          }else{
            // do nothing
            console.log("只有一个leader还往空白上拽，不处理");
            return
          }
        }else{
          // sl1.member=>sl1.空白
          console.log("组内交换 sl1.member=>sl1.空白");
          sl.memList.push(man.mem)
          sl.memList.splice(man.i,1)
        }
      }else{
        // 组间交换 
        if(man.isLeader){
          // sl2.leader =>sl.空白
          console.log("sl2.leader =>sl.空白");
          if(sl.leader==null){
            sl.leader = man.mem
          }else{
            sl.memList.push(man.mem)
          }
          
          
          if(man.sl.memList!=null && man.sl.memList.length>0){
            man.sl.leader = man.sl.memList[0]
            man.sl.memList.splice(0,1)
          }else{
            man.sl.leader = null;
          }
        }else{
          // sl2.member=>sl.空白

          console.log("sl2.member=>sl.空白");
          man.sl.memList.splice(man.i,1)
          if(sl.leader==null){
            console.log(111);
            sl.leader=man.mem;
          }else{
            console.log(2222);
            sl.memList.push(man.mem)
          }
          
        }
      }

    
    }
}


/** --------- utils -------- */
const findMemFromTeamOnlyById = function ( memid) {
  let retMan = {};
  tizhi.value.some((item) => {

      item.slList.some((sl) => {
          
          if (sl.leader != null && sl.leader.id == memid) {
            // return this leader
            console.log("find leader.");
            retMan = { prj:item,sl: sl, mem: sl.leader, i: 0, isLeader: true, findFromFreeman:false };
            return true;
          }

          sl.memList.some((mem, i) => {
            if (mem.id == memid) {
              // return this member.
              console.log("find mem.");
              retMan = { prj:item,sl: sl, mem: mem, i: i, isLeader: false,findFromFreeman:false };
              console.log("findMemFromTeam==", retMan);
              return true;
            }
          });

          
      
      });

    
   
  });

  return retMan;
};
const findMemFromTeam = function (prjid, slid, memid) {
  let retMan = {};
  tizhi.value.some((item) => {
    if (item.prjId == prjid) {
       console.log("find prj");

      item.slList.some((sl) => {
        if (sl.slid == slid) {
           console.log("find sl");
          if (sl.leader != null && sl.leader.id == memid) {
            // return this leader
            console.log("find leader.");
            retMan = { prj:item,sl: sl, mem: sl.leader, i: 0, isLeader: true, findFromFreeman:false };
            return true;
          }

          sl.memList.some((mem, i) => {
            if (mem.id == memid) {
              // return this member.
              console.log("find mem.");
              retMan = { prj:item,sl: sl, mem: mem, i: i, isLeader: false,findFromFreeman:false };
              console.log("findMemFromTeam==", retMan);
              return true;
            }
          });

          return true;
        }
      });

      return true;
    }
  });

  return retMan;
};

const findManFromFreeman = function (manid) {
  let retMan = {};
  freeman.value.some((item, i) => {
    if (item.id == manid) {
      retMan = { mem: item, i: i,findFromFreeman:true };
      return true;
    }
  });
  return retMan;
};

// for test
 const  fetchAll = async function(){
  let currentDateParam = _dateTimeFormatter2Number(wkDate.value);

  await axios.post('http://localhost:8081/api/alltizhi',currentDateParam).then(function(response){
   console.log(response.data);
   teamdata = response.data;
   tizhi.value = response.data.tizhi;
   console.log("set oldtizhi. 822");
   oldtizhi = JSON.parse(JSON.stringify(response.data.tizhi)) // OK，深拷贝对象就是所有属性的值都复制了一份。
   freeman.value = response.data.freeman;
  }).catch(function(error){
    console.log(error);
  })

  console.log("end of fetchAll");

}

var newTizhiRecords = []
var updateTizhiRecords = [] //{"tizhiId":tizhiId,"slid":v.slid,"gangwei":v.employee.gangwei}

const SaveToDB = function(){
  console.log("SaveToDB");
  newTizhiRecords = []; // 首先清空。
 
  // 新加入到体制里面还没保存的freeman挑出来，并加工出开始和结束时间。
  tizhi.value.some(item=>{
    console.log(item.prjId);
    item.slList.some( sl=>{
      console.log(sl.slid);
      console.log(sl.leader);
      if(sl.leader!=null && sl.leader.isFree){
        newTizhiRecords.push(changeFreemanToRecord(sl.leader,item.prjId,sl.slid,"SL"));// TODO 
        
      }
      if(sl.memList != null ){
        sl.memList.some(mem=>{
          console.log("mem==>",mem);
          if(mem.isFree){
            newTizhiRecords.push(changeFreemanToRecord(mem,item.prjId,sl.slid,"MEM"));// TODO 
          }
        })
      }
    })
  })

  // newTizhiRecord send to backend.
  // debugger 

 

  // 比较原有体制和新体制的差别，把应插入记录放入插入集，把应更新记录放到更新集。
  // 原有体制数据里有tizhiId，要么更新岗位，要么更新小组id。就这两个。而记录数不会变化。新数据和旧数据的记录数不会变化。
  // 所以，只需按照tizhiId重新排序，比较有变化的就放入更新池即可。
  // DB里更新的方法是，在该tizhiId记录上修正endDate=wkDate -1. 然后新创建一条记录wkDate～该记录的endDate。 就是Update一条，然后Insert一条。
   getChangedTizhiRecords()


   // 等tizhi的DB操作数据梳理完成后统一发送URL请求。
  const {data1,error1} = useFetch('http://localhost:8081/api/tzbatchins',{newTizhiRecords,updateTizhiRecords,currentDateParam})
  if(error1 !=null)
  {
    console.log(error1);
  } else{
    console.log("插入成功",data1);
  }
}

//  比较原有体制和新体制的差别，把应更新记录放到更新集。
const getChangedTizhiRecords = function(){

  updateTizhiRecords = []; // {"tizhiId":tizhiId,"slid":v.slid,"gangwei":v.employee.gangwei}


  // old
  var oldTizhiMap = new Map();
  oldtizhi.forEach(prj => {
    console.log(prj.prjName);
    prj.slList.forEach(sl=>{
      if(sl.leader!=null){
        sl.leader.gangwei="SL";
        oldTizhiMap.set(sl.leader.tizhiId,{"prjId":prj.prjId,"slid":sl.slid,"employee":sl.leader})
      }
      if(sl.memList!=null){
        sl.memList.forEach(mem=>{
          mem.gangwei = "MEM"
          oldTizhiMap.set(mem.tizhiId,{"prjId":prj.prjId,"slid":sl.slid,"employee":mem})
        })
      }
    })
  });

  // new
  var newTizhiMap = new Map();
  tizhi.value.forEach(prj => {
    console.log(prj.prjName);
    prj.slList.forEach(sl=>{
      if(sl.leader!=null){
        sl.leader.gangwei="SL";
        newTizhiMap.set(sl.leader.tizhiId,{"prjId":prj.prjId,"slid":sl.slid,"employee":sl.leader})
      }
      if(sl.memList!=null){
        sl.memList.forEach(mem=>{
          mem.gangwei = "MEM"
          newTizhiMap.set(mem.tizhiId,{"prjId":prj.prjId,"slid":sl.slid,"employee":mem})
        })
      }
    })
  });

  // diff
  let oldtmp = null;
  newTizhiMap.forEach((v,tizhiId)=>{
    console.log(tizhiId+"==>"+v.slid+" "+v.employee.id+" "+v.employee.gangwei);
     oldtmp = oldTizhiMap.get(tizhiId);
     if(oldtmp.slid != v.slid || oldtmp.employee.gangwei !=v.employee.gangwei ){
        // 放入池
        updateTizhiRecords.push(
        {
        "tizhiId":tizhiId,
        "xiaozuName":v.slid,
        "projectId":v.prjId,
        "personId":v.employee.id,
        "gangwei":v.employee.gangwei,
        "state":0,
        "startDate":v.employee.startDate,
        "endDate":v.employee.endDate
      })
     }
  })

  // show updatePool
  console.log("updateTizhiRecords.length=="+updateTizhiRecords.length);
  updateTizhiRecords.forEach(poolitem=>{
    console.log(poolitem);
  })
  
}

const changeFreemanToRecord = function(freeman,prjId,slid,gangwei){
  
  let startEndDates = computeStartDate_EndDate(freeman.history)
  // obj.id // tizhi id , increased auto.


  // public String xiaozuName;     //小组名字（组长名字）
	//     public int projectId;   //项目组id
	//     public int personId;    //人员id
	//     public String position;   //职位（组长or组员）
	//     public String state;    //小组状态
	//     public int startDate;
	//     public int endDate;

  return {
    "xiaozuName": slid,
    "projectId":prjId,
    "personId":freeman.id,
    "position" :gangwei,
    "state":0,
    "startDate":startEndDates.startDate,
    "endDate":startEndDates.endDate
  }
}

const computeStartDate_EndDate= function(history){

  let wkDate8 = _dateTimeFormatter2Number(wkDate.value);
  let endDate = null;
  let startDate = null;

  if(history ==null || history.length==0){
    return {"startDate":wkDate8,"endDate":99999999}
  }

  history.some(item=>{
    console.log(item.startDate+" "+ item.endDate);
    if(item.startDate > wkDate8){
      startDate = wkDate8;
      endDate = item.startDate -1 ;
      return ;
    }
  })

  if(startDate == null ){
    startDate = wkDate8;
    endDate = 99999999;
  }

  return {"startDate":startDate,"endDate":endDate}

}

const printOldTizhi = function(){
  console.log("oldtizhi==>",oldtizhi);
}


const popupTigger = ref({
   buttonTrigger :false
})

const toggle =function(){
  popupTigger.value.buttonTrigger = ! popupTigger.value.buttonTrigger
}
</script>

<template>
  <div id="tmp2team">
    <div id="top" class="top">
      <div v-if="error">Oops! Error encountered: {{ error.message }}</div>
      <div class="consoler" v-else-if="teamdata">
        <!-- Data loaded:
        <pre>{{ teamdata.freeman.length }}</pre> -->
        <MyDateSlider @dateChanged="dateChangedHandler" @dateChangeDone="fetchAll"></MyDateSlider>
        <span class="wkdate">调整日期：{{ formatedWkdateStr }}</span>
      </div>
      <div v-else>Loading...</div>
    
     
     <!-- <button @click="printTiZhi">printTizhiObj</button> <button @click="printOldTizhi">oldTizhiPrint</button> -->
     
       
    </div>
    <div id="main">
      <div class="left">
        <div class="leftTop">
          <span >暂存区</span>
          <el-button @click="toggle()" type="warning" :icon="Search" circle />
          <teleport to="body">
            <popUp 
              v-if="popupTigger.buttonTrigger" 
              :togglePopup="()=>{toggle() }"
              :freeman = "freeman"
              :wkDate ="wkDate"
              >
              <h1> free man terms: </h1>

            </popUp>
           </teleport>
          
        
        </div>

        <el-affix :offset="120">
          <div
            @dragover="dragOverHandler($event)"
            @drop="tmpzoneDropHandler($event)"
            class="leftMiddle"
          >
            <!-- freeman -->

              <div
              draggable="true"
              @dragstart="dragStartHandle(man, $event)"
              class="freechild"
              v-for="(man, index) in freeman"
              :key="man.id"
              :id="man.id"
             > 
             <freechild :manid="man.id" :freechild="man"></freechild>
             
            
              </div>
            
          
          </div>
        </el-affix>
      </div>
      <div class="right">
        <div class="rightTop"><span>契约中体制</span>  <el-button @click="SaveToDB" type="success">保存</el-button></div>
        <div class="rightMiddle">
          <!-- prject -->
          <div
            class="project"
            :id="prj.prjId"
            v-for="prj in tizhi"
            :key="prj.prjId"
          >
            <div class="prjname">{{ prj.prjId }} {{ prj.prjName }}</div>
            <div class="slList">
              <!-- sl -->
              <div
                @dragover="dragOverHandler($event)"
                @drop="slDropHandler(sl, $event)"
                class="sl"
                v-for="sl in prj.slList"
                :id="sl.slid"
                :key="sl.slid"
              >
                <div class="sltitle">{{ sl.slid }}</div>
                <!-- leader -->
                <div
                  draggable="true"
                  @dragstart="dragStartHandle(sl.leader, $event)"
                  :class="
                    sl.leader != null &&
                    Object.hasOwn(sl.leader, 'isFree') &&
                    sl.leader.isFree
                      ? 'freeleader'
                      : 'leader'
                  "
                  v-if="sl.leader"
                  :id="sl.leader.id"
                >
                  {{sl.leader.id}} {{sl.leader.level }} {{ sl.leader.name }}
                </div>
                <!-- <div 
                      class="leader"
                      v-else="sl.leader" > 没leader</div> -->
                <!-- member -->
                <div
                  :class="
                    Object.hasOwn(mem, 'isFree') && mem.isFree
                      ? 'freemember'
                      : 'member'
                  "
                  draggable="true"
                  @dragstart="dragStartHandle(mem, $event)"
                  v-for="mem in sl.memList"
                  :id="mem.id"
                  :key="mem.id"
                >
                <memCom :mem="mem"></memCom>
                <!-- {{ mem.id }} {{ mem.level }} {{ mem.name }} -->
                </div>
              </div>

              <div class="btndiv">
                <el-button
                  type="primary"
                  :id="'addsl' + prj.prjId"
                  @click="addsl(prj.slList)"
                  >add sl</el-button
                >
                <el-button
                  type="primary"
                  :id="'delsl' + prj.prjId"
                  @click="delsl(prj.slList)"
                >
                  del sl
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <el-backtop :right="100" :bottom="100" />
</template>

<style>
* body {
  margin: 0;
  box-sizing: border-box;
}

#main {
  display: flex;
  justify-content: flex-start;
  height: 100vh;
  /* border: 1px solid red; */
}

.top{
  margin-bottom: 5px;
  margin-left:5px;
}

.left {
  height: 100%;
  width: 20%;
  /* border: 1px solid blue; */
}
.right {
  height: 100%;
  width: 80%;
  /* border: 1px solid green; */
}
.leftTop {
  height: 50px;
  border: 1px solid black;
  text-align: center;
  display: flex;
  place-items: center;
}

.leftTop span {
  width: 50%;
  font-size:20px;
}

.leftTop button {
  
}


.rightMiddle {
  height: 100%;
}
.rightTop {
  height: 50px;
  border: 1px solid black;
  text-align: center;
  display: flex;
  place-items: center;
}
.rightTop span{
  width:50%;
  font-size:20px;
}
.rightTop button{
  width:10%;
}

.leftMiddle {
  /* border: 1px solid black; */
  height: 400px;
  /* height: 100%; */
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  align-items: flex-start;
}
.freechild {
  border: 2px dashed blue;
  height: 25px;
  width: 150px;
  margin: 3px;
  background: #7ee2f4;
}
.project {
  background: #f9b686;

  border: 1px solid #f46e0e;
  display: flex;
  /* justify-content: ; */
}
.prjname {
  width: 100px;
}
.slList {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
}
.sl {
  /* border: 1px solid blue; */
  height: 200px;
  width: 150px;
  /* background: linear-gradient(45deg,#fb3,#58a ,#58a,#fb3 ,#fb3,#58a ); */
}
.sltitle {
  background: white;
}
.leader {
  border: 1px solid red;
  background: #eb6b26;
}
.freeleader {
  border: 2px dashed red;
  background: #7ee2f4;
}
.member {
  border: 1px solid black;
  background: #fff701;
  margin: 2px;
}
.freemember {
  border: 2px dashed blue;
  background: #7ee2f4;
}
.el-notification.right { /** .right会设置 */
    width: 400px;
    height: 120px;
}


.consoler{
  display: flex;
  justify-content: start;
}
.wkdate{
  padding: 4px;
  margin: 3px;
  font-size:20px;
  margin-left:10px;
  color:black;

}
</style>